package com.cs

import android.provider.Settings
import kotlinx.coroutines.*
import org.junit.Test
import kotlin.system.measureTimeMillis

class test_coroutines {


    @Test
    fun show() = runBlocking{
//        println("hello world!")

        println("thread name:${Thread.currentThread().name}")

         val jobDefer: Deferred<Int> =  async {
            println("launch--begin:${Thread.currentThread().name}")
            delay(1000)
            println("launch--end:${Thread.currentThread().name}")
            12
        }

        val result = jobDefer.await()
        println("result is $result")
        println("---- end")
    }

    @Test
    fun testCancel() = runBlocking {
        println("thread name:${Thread.currentThread().name}")

        val job = launch(Dispatchers.Default){
            try {
                for(i in 0..500){
                    print("$i.")
                    delay(5)
                }
            }catch (ex:CancellationException){
                println("\n 收到cancel exception")
            }finally {
                println("\n finalllxxxx")
            }
        }

        delay(10)
        job.cancelAndJoin()
        println("\nall end!")
    }


    @Test
    fun exeSquence() = runBlocking{
        println("thread name:${Thread.currentThread().name}")

        delay(1000)
        println("hello 1")

        val time = measureTimeMillis {
            val hello:Deferred<String> = async { getMessageOne() }
            val world : Deferred<String> = async { getMessageTwo() }
            println("this is run at ${Thread.currentThread().name}, and value is ${hello.await() + world.await()}")
        }

        println("hello world spend: ${time}ms")
        println("----- end")
    }


    suspend fun getMessageOne():String{
        delay(1000)
        println("getMessageOne->${Thread.currentThread().name}")
        return "Hello"
    }

    suspend fun getMessageTwo():String{
        delay(1200)
        println("getMessageTwo->${Thread.currentThread().name}")
        return "World!"
    }

    @Test
    fun testContext() = runBlocking{
        println("start---${Thread.currentThread().name}")

        launch {
            println("C1......${Thread.currentThread().name}")
        }

        println("end----------------")
    }

}